<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <el-row type="flex" justify="end">
          <el-button size="small" type="primary" @click="showDialog('0','1')">添加权限</el-button>
        </el-row>
      </template>
      <el-table
        :data="tableData"
        stripe
        row-key="id"
        border
        default-expand-all
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        style="width: 100%"
      >
        <el-table-column label="权限名称" prop="title" />
        <el-table-column label="权限标识" prop="code" />
        <el-table-column label="权限描述" prop="description" />
        <el-table-column label="操作">
          <template v-slot="{row}">
            <el-button type="primary" size="small" @click="showDialog(row.id,'2')">添加子权限</el-button>
            <el-button type="success" size="small" @click="editFn(row.id)">编辑</el-button>
            <el-button type="danger" size="small" @click="delFn(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <AddPermission ref="AddPermission" :visible-dialog.sync="visibleDialog" @updataFn="getPermissionList" />
  </div>
</template>

<script>
import { permissionList, delPermission, getPermissionById } from '@/api/permissions'
import AddPermission from './components/addPermission.vue'
export default {
  components: {
    AddPermission
  },
  data() {
    return {
      tableData: [],
      visibleDialog: false
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    async  getPermissionList() {
      const res = await permissionList({
        _limit: 100,
        _start: 0
      })
      this.tableData = this.listToTree(res.data, '0')
      console.log('权限', res)
    },
    showDialog(pid, type) {
      this.$refs.AddPermission.formData.pid = pid.toString()
      this.$refs.AddPermission.formData.type = type
      this.visibleDialog = true
    },
    listToTree(arr, id) {
      const list = []
      arr.forEach(item => {
        if (item.pid === id.toString()) {
          list.push(item)
          // 获取子部门
          item.children = this.listToTree(arr, item.id)
        }
      })
      return list
    },
    delFn(id) {
      this.$confirm('确定删除吗？', '提示', {
        type: 'error'
      }).then(async() => {
        await delPermission(id)
        this.$message.success('删除成功！')
        this.getPermissionList()
      }).catch((error) => {
        this.$message.error('取消删除！')
        console.log(error)
      })
    },
    async editFn(id) {
      const res = await getPermissionById(id)
      this.$refs.AddPermission.formData = res.data
      this.visibleDialog = true
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
